<template>
	<view class="activity-detail">
		<!-- 顶部导航栏 -->

		<!-- 主要内容区域 -->
		<view class="content-scroll">
			<!-- 活动信息卡片 -->
			<view class="activity-card">
				<view class="card-header">
					<view class="activity-title">{{ model.title }}</view>
					<view class="activity-subtitle">{{ model.subtitle }}</view>
					<view class="host-info">
						<text class="host-label">主理人：</text>
						<text class="host-name">{{ model.userName }}</text>
						<view class="contact-btn" @click="handleContact">
							<text class="contact-icon">📞</text>
						</view>
					</view>
				</view>

				<view class="activity-description">
					{{ model.content }}
				</view>

				<!-- 活动时间和参与者信息 -->
				<view class="activity-info-card">
					<view class="info-row">
						<view class="info-left">
							<text class="info-label">开始时间</text>
							<text class="info-label">空余车位</text>
						</view>
						<view class="info-right">
							<text class="info-value">{{ formatDateTime(model.beginDate) }}</text>
							<text class="info-value" v-if="model.waitingNum>0 ">{{ model.waitingNum }}</text>
							<text class="info-value"  v-else>满员</text>
						</view>
					</view>

					<!-- 参与者头像列表 -->
					<view class="participants-section">
						<view class="participants-avatars">
							<image
								v-for="(participant, index) in model.joins"
								:key="participant.id"
								:src="participant.avatar"
								class="participant-avatar"
								:class="{ 'has-badge': participant.badge }"
								mode="aspectFill"
							>
							</image>
							<button class="add-participant" open-type="share"  v-if="model.waitingNum>0">
								<text class="add-icon">+</text>
								<text class="add-text">邀请</text>
							</button>
						</view>
					</view>
				</view>

				<!-- 商家信息 -->
				<view class="merchant-info">
					<view class="merchant-row">
						<text class="merchant-label">商家信息：</text>
						<text class="merchant-address">{{ model.shopAddress }}</text>
						<view class="location-actions">
							<view class="location-btn" @click="handleNavigation">
								<text class="location-icon">🧭</text>
							</view>
							<view class="phone-btn" @click="handleCall">
								<text class="phone-icon">📞</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部占位 -->
			<view class="bottom-placeholder"></view>
		</view>

		<!-- 底部报名栏 -->
		<view class="bottom-bar" v-if="shopJoin">
			<view class="price-section">
				<text class="price-label">报名费：</text>
				<text class="price-value">¥{{ model.fee }}</text>
			</view>
			<view class="join-section" @click="handleJoin">
				<view
					class="join-btn"
					:class="getJoinButtonClass()"
					:disabled="isJoinDisabled()"
				>
					<text class="join-text">{{ getJoinButtonText() }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { one } from '@/common/data.js'
import {pay, post} from "../../common/api";

// 活动数据
const model = ref({

})

const shopJoin = ref(true);

// 加载活动数据
const loadActivityData = async (options) => {
	try {
		const activityId = options.id || 1
		const res = await one('front_topic_view', { id: activityId })

		if (res.code === 200) {
			model.value = {
				...res.data
			}
		} else {
			uni.showToast({
				title: res.msg || '加载失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('加载活动数据失败:', error)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	}
}

onLoad(async (options) => {
	await loadActivityData(options);
	if(options.shopJoin==='2'){
		shopJoin.value=false;
	}
})

// 分享给好友
onShareAppMessage(() => {
	return {
		title: model.value.title || '精彩活动邀请',
		path: `/pages/topic/index?id=${model.value.id}`,
		imageUrl: model.value.image || '' // 可选：分享图片
	}
})

// 分享到朋友圈（如果支持）
onShareTimeline(() => {
	return {
		title: model.value.title || '精彩活动邀请',
		path: `/pages/topic/index?id=${model.value.id}`,
		imageUrl: model.value.image || ''
	}
})

// 分享功能
const handleShare = () => {
	uni.showShareMenu({
		success: () => {
			console.log('分享成功')
		}
	})
}

// 联系主理人
const handleContact = () => {
	uni.showActionSheet({
		itemList: ['拨打电话', '发送消息'],
		success: (res) => {
			if (res.tapIndex === 0) {
				uni.makePhoneCall({
					phoneNumber: model.value.userPhone
				})
			}
		}
	})
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
	if (!dateTimeStr) return ''

	try {
		// 将 %Y-%m-%d %H:%i:%s 格式转换为 JavaScript Date 对象
		const date = new Date(dateTimeStr)

		// 格式化为 YYYY-MM-DD HH:mm
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const hours = String(date.getHours()).padStart(2, '0')
		const minutes = String(date.getMinutes()).padStart(2, '0')

		return `${year}-${month}-${day} ${hours}:${minutes}`
	} catch (error) {
		console.error('日期格式化失败:', error)
		return dateTimeStr
	}
}

// 邀请好友功能通过 button open-type="share" 实现

// 导航功能
const handleNavigation = () => {
	uni.openLocation({
		latitude: model.value.shopLat,
		longitude: model.value.shopLng,
		name: '活动地点',
		address: model.value.shopAddress
	})
}

// 拨打电话
const handleCall = () => {
	uni.makePhoneCall({
		phoneNumber: model.value.shopPhone
	})
}

// 获取报名按钮样式
const getJoinButtonClass = () => {
	if (model.value.joinState === 1) return 'joined'
	if (model.value.waitingNum === 0) return 'full'
	if (model.value.status === 'ended') return 'ended'
	return 'normal'
}

// 判断按钮是否禁用
const isJoinDisabled = () => {
	return model.value.joinState === 1 || model.value.waitingNum === 0 || model.value.status === 'ended'
}

// 获取按钮文本
const getJoinButtonText = () => {
	if (model.value.joinState === 1) return '已报名'
	if (model.value.waitingNum === 0) return '已满员'
	if (model.value.status === 'ended') return '已结束'
	return '报名'
}

// 处理报名
const handleJoin = () => {
	if (model.value.joinState === 1) {
		// 已报名用户不能再次操作
		return
	}
	if (model.value.waitingNum === 0) {
		// 已报名用户不能再次操作
		return
	}

	uni.showModal({
		title: '确认报名',
		content: `确定要报名参加"${model.value.title}"吗？\n报名费：¥${model.value.fee}`,
		success: (res) => {
			if (res.confirm) {
               joinNotice();
			}
		}
	})
}


const joinNotice = async () => {
  const param = {
    topic: model.value.id,
	payConfig: "ego"
  }
  let res = await post("/topicJoin/createExt", param);
  if(res.code!=200){
    uni.showToast({
      title: res.msg,
      icon: 'none',
    });
    return;
  }

  if (res.data.needPay){
    pay(res.data.pay.pay,()=>{
        uni.showModal({
        	title:"报名成功",
			showCancel:false,
			success: () => {
				// 重新加载数据
				uni.reLaunch({
					url:"/pages/index/index"
				})
			}
        })
    })
  }else{
	uni.showModal({
		title:"报名成功",
		showCancel:false,
		success: () => {
			// 重新加载数据
			uni.reLaunch({
				url:"/pages/index/index"
			})
		}
	})
  }

}

</script>

<style scoped>
.activity-detail {
	background: #f5f5f5;
	min-height: 100vh;
}

/* 顶部导航栏 */
.nav-bar {
	background: white;
	border-bottom: 1px solid #f0f0f0;
}

.nav-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 20px;
}

.nav-title {
	font-size: 18px;
	font-weight: 600;
	color: #333;
}

.nav-right {
	display: flex;
	align-items: center;
}

.share-btn {
	display: flex;
	align-items: center;
	gap: 4px;
}

.share-icon {
	font-size: 18px;
	color: #007AFF;
}

.share-text {
	font-size: 16px;
	color: #007AFF;
}

/* 内容滚动区域 */
.content-scroll {
	height: calc(100vh - 160px);
	padding: 20px;
}

/* 活动卡片 */
.activity-card {
	background: white;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
	margin-bottom: 16px;
}

.activity-title {
	font-size: 24px;
	font-weight: 700;
	color: #333;
	text-align: center;
	margin-bottom: 8px;
}

.activity-subtitle {
	font-size: 18px;
	color: #666;
	text-align: center;
	margin-bottom: 16px;
}

.host-info {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8px;
	margin-bottom: 16px;
}

.host-label {
	font-size: 16px;
	color: #333;
}

.host-name {
	font-size: 16px;
	font-weight: 600;
	color: #333;
}

.contact-btn {
	padding: 4px 8px;
	background: #f0f0f0;
	border-radius: 4px;
}

.contact-icon {
	font-size: 16px;
}

.activity-description {
	font-size: 14px;
	color: #666;
	line-height: 1.6;
	margin-bottom: 20px;
	text-align: justify;
}

/* 活动信息卡片 */
.activity-info-card {
	background: #AA0E99;
	border-radius: 12px;
	padding: 6px;
	margin-bottom: 16px;
}

.info-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 0px;
	padding: 10rpx;
}

.info-left {
	display: flex;
	flex-direction: column;
	gap: 8px;
	color: #fff;
	font-weight: 600;
}

.info-right {
	display: flex;
	flex-direction: column;
	gap: 8px;
	text-align: right;
}

.info-label {
	font-size: 14px;
}

.info-value {
	font-size: 16px;
	color: white;
	font-weight: 500;
}

/* 参与者头像区域 */
.participants-section {
	border-top: 1px solid #444;
	padding-top: 16px;
	background-color: #fff;
	padding: 20rpx;
	border-radius: 20rpx;
}

.participants-avatars {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 12px;
	flex-wrap: wrap;
}

.participant-avatar {
	width: 48px;
	height: 48px;
	border-radius: 24px;
	border: 2px solid #444;
	position: relative;
}

.participant-avatar.has-badge::after {
	content: '';
	position: absolute;
	bottom: -2px;
	right: -2px;
	width: 16px;
	height: 16px;
	background: #ff69b4;
	border-radius: 8px;
	border: 2px solid #2c2c2c;
}

.add-participant {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4px;
	padding: 6px;
	background: transparent;
	border: none;
	font-size: inherit;
	line-height: inherit;
	margin: 0;
	box-sizing: border-box;
	flex-shrink: 0;
	width: auto;
	height: auto;
	min-width: auto;
	min-height: auto;
}

.add-participant::after {
	display: none;
}

.add-icon {
	width: 56rpx;
	height: 56rpx;
	border: 2px dashed #666;
	border-radius: 24px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
	line-height: 56rpx;
	color: #666;
}

.add-text {
	font-size: 20rpx;
	color: #999;
}

/* 商家信息 */
.merchant-info {
	border-top: 1px solid #f0f0f0;
	padding-top: 16px;
}

.merchant-row {
	display: flex;
	align-items: center;
	gap: 8px;
}

.merchant-label {
	font-size: 14px;
	color: #333;
}

.merchant-address {
	flex: 1;
	font-size: 14px;
	color: #666;
}

.location-actions {
	display: flex;
	gap: 8px;
}

.location-btn, .phone-btn {
	width: 32px;
	height: 32px;
	background: #f0f0f0;
	border-radius: 16px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.location-icon, .phone-icon {
	font-size: 16px;
}

.bottom-placeholder {
	height: 80px;
}

/* 底部报名栏 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: white;
	padding: 16px 20px;
	border-top: 1px solid #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	safe-area-inset-bottom: env(safe-area-inset-bottom);
}

.price-section {
	display: flex;
	align-items: baseline;
	gap: 4px;
}

.price-label {
	font-size: 14px;
	color: #666;
}

.price-value {
	font-size: 20px;
	font-weight: 700;
	color: #ff9500;
}

.join-section {

}

.join-btn {
	background: #AA0E99;
	color: white;
	border: none;
	border-radius: 20rpx;
	padding: 16rpx 36rpx;
	display: flex;
	align-items: center;
	gap: 6px;
	font-size: 15px;
	font-weight: 600;
	justify-content: center;
	box-shadow: 0 2px 8px rgba(255, 149, 0, 0.3);
	transition: all 0.3s ease;
}

.join-btn:active {
	transform: translateY(1px);
	box-shadow: 0 1px 4px rgba(255, 149, 0, 0.3);
}

.join-btn.joined {
	background: linear-gradient(135deg, #e0e0e0, #d0d0d0);
	color: #999;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.join-btn.full, .join-btn.ended {
	background: linear-gradient(135deg, #ccc, #bbb);
	color: #999;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.join-btn:disabled {
	opacity: 0.7;
	transform: none;
}

.join-icon {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 16px;
	height: 16px;
}

.join-text {
	font-size: 15px;
	font-weight: 600;
}
</style>
